﻿/// <summary>
/// Developer: CHOOI KAH WAI
/// Last Modified: 16/11/2009
/// </summary>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ARSS
{
    /// <summary>
    /// System log
    /// </summary>
    public class Logger
    {
        #region Variables

        /// <summary>
        /// Singleton variable
        /// </summary>
        private static Logger thisInstance = new Logger();

        /// <summary>
        /// The log file
        /// </summary>
        private StreamWriter logFile;

        /// <summary>
        /// Is activated?
        /// </summary>
        private bool isActivated;

        #endregion

        #region Properties

        /// <summary>
        /// Logger Singleton
        /// </summary>
        public static Logger Instance { get { return thisInstance; } }

        /// <summary>
        /// Logger activation state
        /// </summary>
        public bool IsActivated
        {
            set
            {
                isActivated = value;
                if (this.isActivated && this.logFile == null)
                {
                    Directory.CreateDirectory(DirectoryName);
                    // Create new log file
                    string filepath = string.Format("{0}\\{1}\\log_{1}_{2}.txt",
                                                Directory.GetCurrentDirectory(),
                                                DirectoryName,
                                                DateTime.Today.ToString("ddMMyyyy"),
                                                DateTime.Now.ToString("hhmm"));

                    this.logFile = new StreamWriter(filepath);
                    this.logFile.AutoFlush = true;
                }

                // Stop logging.
                if (!isActivated && this.logFile != null)
                {
                    this.logFile.Close();
                    this.logFile = null;
                }
            }
        }

        /// <summary>
        /// Directory name for current log file
        /// </summary>
        public string DirectoryName { get; set; }

        #endregion

        #region Functions

        /// <summary>
        /// Destructor
        /// </summary>
        ~Logger()
        {
            try
            {
                this.logFile.Close();
            }
            catch (Exception ex)
            {
            }
        }
        /// <summary>
        /// Write the log message
        /// </summary>
        /// <param name="logMessage">Message to log</param>
        public void Log(string logMessage)
        {
            if(isActivated)
                this.logFile.WriteLine(DateTime.Now.ToString("hh:mm:ss") + " : " + logMessage);
        }

        #endregion
    }
}
